##########################################################################################

library(data.table)
library(optparse)

##########################################################################################

option_list <- list(
    make_option(c("--sample"), type = "character"),
    make_option(c("--input_file"), type = "character"),
    make_option(c("--purity_file"), type = "character"),
    make_option(c("--out_path"), type = "character")
)

if(1!=1){
    
    sample <- "HUAXI0015905855-T"
    purity_file <- "/public/home/xxf2019/20220205_lungSomatic/Analysis_LUAD/titan/Purity_titan.final.tsv"
    input_file <- "/public/home/xxf2019/20220205_lungSomatic/Analysis_LUAD/mutationTime/result/HUAXI0015905855-T_CCF_mutTime.tsv"
    out_path <- "/public/home/xxf2019/20220205_lungSomatic/Analysis_LUAD/mutationTime/distribution/"

}

###########################################################################################

parseobj <- OptionParser(option_list=option_list, usage = "usage: Rscript %prog [options]")
opt <- parse_args(parseobj)
print(opt)

sample <- opt$sample
purity_file <- opt$purity_file
input_file <- opt$input_file
out_path <- opt$out_path

###########################################################################################

## Purity
dat_purity <- fread(purity_file)
purity <- subset(dat_purity , Sample == sample)$Purity
ploidy <- subset(dat_purity , Sample == sample)$Ploidy


## MutaionTime
dat_ccf <- fread(input_file)
MutaionTimeClass <- gsub( " " , "" , names(which.max(table(dat_ccf$CLS))))

if(is.na(table(dat_ccf$CLS)["clonal [early]"])){
    clone_early_num=0
}else{
    clone_early_num=table(dat_ccf$CLS)["clonal [early]"]
}

if(is.na(table(dat_ccf$CLS)["clonal [late]"])){
    clone_late_num=0
}else{
    clone_late_num=table(dat_ccf$CLS)["clonal [late]"]
}

if(is.na(table(dat_ccf$CLS)["clonal [NA]"])){
    clone_NA_num=0
}else{
    clone_NA_num=table(dat_ccf$CLS)["clonal [NA]"]
}

if(is.na(table(dat_ccf$CLS)["subclonal"])){
    subclonal_num=0
}else{
    subclonal_num=table(dat_ccf$CLS)["subclonal"]
}


dat <- data.frame(Sample = sample , Purity = purity , Ploidy = ploidy ,
    clonal_early = clone_early_num , clonal_late = clone_late_num , 
    clonal_NA = clone_NA_num , subclonal = subclonal_num , Type =  MutaionTimeClass )


image_name <- paste0(out_path , "/" , sample , "_mutTime_stat.tsv")
write.table(dat, image_name , sep = "\t" , row.names = F , quote = F )
